//
//  LeveragedTradeView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/7.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
let selectTag = 1000
let selectMoreTage = 2000

class LeveragedTradeView: UIView {
    var dataSource: LeveragedTradeViewController!

    lazy var footView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        return view
    }()
    
    ///最新价
    lazy var numberLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont(name: "Helvetica-Bold", size: 30)
        label.text = "0.0000"
        label.textColor = UIColor(hexStr: "eb4949")
        return label
    }()
    
    ///当前法币价格
    lazy var moneyLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 11)
        label.text = "≈0.000"
        label.textColor = kTextColor
        return label
    }()
    
    ///涨幅
    lazy var flyLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 11)
        label.text = "%0.00"
        label.textColor = UIColor(hexStr: "#eb4949")
        return label
    }()
    lazy var chartView: CHKLineChartView = {
        let view = CHKLineChartView()
        return view
    }()
    
    ///高 低 24h
    lazy var infoLabels: [UILabel] = []
    
    var buyButton: UIButton?
    var sellButton: UIButton?
    
    var viewModel: KlineViewModel {
        return self.dataSource.viewModel
    }
    
    var selectBtnArr:[KlineSelectButton] = []
    
    let nameArr = [kText("分时"),"15\(kText("分"))","1\(kText("小时"))","4\(kText("小时"))",kText("日线"),"\(kText("更多"))|2"]
    


    var dataArray = [Array<Float>]()
    var vprintf: String = ""
    
    init(dataSource: LeveragedTradeViewController) {
        super.init(frame: CGRect.zero)
        self.dataSource = dataSource
        self.setUpUI()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI() -> Void {
       self.addSubview(numberLabel)
        numberLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(21)
            make.left.equalToSuperview().offset(16)
        }
        
        self.addSubview(moneyLabel)
        moneyLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(64)
        }
        
        self.addSubview(flyLabel)
        flyLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(110)
            make.centerY.equalTo(moneyLabel)
        }
        
        let names = [kText("高"),kText("低"),"24h"]
        
        for i in 0..<3 {
            let nameLabel = UILabel()
            nameLabel.font = UIFont.systemFont(ofSize: 12)
            nameLabel.textColor = KUseTitleColor
            nameLabel.text = names[i]
            self.addSubview(nameLabel)
            nameLabel.snp.makeConstraints { (make) in
                make.right.equalToSuperview().offset(-96)
                make.top.equalTo(20+i*22)
            }
            
            let inforLabel = UILabel()
            inforLabel.text = "0.0000"
            inforLabel.textColor = kTextColor
            inforLabel.font = UIFont.systemFont(ofSize: 12)
            self.addSubview(inforLabel)
            inforLabel.snp.makeConstraints { (make) in
                make.centerY.equalTo(nameLabel)
                make.right.equalToSuperview().offset(-15)
            }
            infoLabels.append(inforLabel)
        }
        
       
        for i in 0 ..< nameArr.count {
            let btn = KlineSelectButton()
            self.addSubview(btn)
            btn.tag = selectTag + i
            btn.title = nameArr[i]
            btn.click = {[weak self](btn) in
                self?.selectAction(sender: btn)
            }
            selectBtnArr.append(btn)
            btn.snp.makeConstraints { (make) in
                make.left.equalTo(CGFloat(i) * kSCREEN_WIDTH/6)
                make.top.equalToSuperview().offset(91)
                make.width.equalTo(kSCREEN_WIDTH/6)
                make.height.equalTo(25)
            }  
        }
        
        self.addSubview(chartView)
        chartView.delegate = self
        chartView.style = CHKLineChartStyle.customDark
        chartView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(116)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-83)
        }
       
        self.addSubview(footView)
        footView.backgroundColor = UIColor.clear
        footView.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(83)
        }
        
        for i in 0..<2 {
            let btn = UIButton()
            if i == 0 {
                self.buyButton = btn
            }else {
                self.sellButton = btn
            }
            btn.layer.cornerRadius = 3
            btn.setTitle(i==0 ? kText("买入(看涨)") : kText("卖出(看跌)"), for: UIControlState.normal)
            btn.setTitleColor(UIColor(hexStr: "#f7f8f9"), for: UIControlState.normal)
            btn.addTarget(self, action: #selector(buyBtnAction(sender:)), for: UIControlEvents.touchUpInside)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
            btn.backgroundColor = i==0 ? kGreenColor : kRedColor
            let left = 15.00 + Double(i)*Double(((kSCREEN_WIDTH-45)/2 + 15))
            footView.addSubview(btn)
            btn.snp.makeConstraints { (make) in
                make.left.equalTo(left)
                make.centerY.equalToSuperview()
                make.width.equalTo((kSCREEN_WIDTH-45)/2)
                make.height.equalTo(42)
            }
        }
    }
    
    func loadData() {
        let viewModel = self.dataSource.viewModel
        viewModel.loadData()
        let period = viewModel.peroid
        viewModel.peroid = ""
        for btn in selectBtnArr {
            if btn.title == period {
                self.selectAction(sender: btn)
            }
        }
    }

    @objc func selectAction(sender: KlineSelectButton) {
        if sender.title != kText("更多") {
            for view in selectBtnArr {
                view.isSelected = false
            }
            sender.isSelected = true
        }
        if sender.buttonType != .normal {
            //处理更多弹框
            guard let view = KlineSelectView.loadFromNib() as? KlineSelectView else {return}
            view.buttonClick = {[weak view] subBtn in
                self.moreClick(period: subBtn.titleLabel!.text!, popView: view!)
            }
            let rect = sender.convert(sender.bounds, to: nil)
            let pop = PopView(contentView: view)
            pop.delegate = self
            sender.backgroundColor = view.backgroundColor
            pop.enableAnyTouchDissmiss()
            pop.hubColor = UIColor.clear
            view.addShadow(shadowOffset: CGSize(width: 0, height: 3))
            pop.pop(inRect: CGRect(x: 0, y: rect.maxY , width: kSCREEN_WIDTH, height: 50))
            
        }else {
            for btn in self.selectBtnArr {
                if btn.buttonType != .normal {
                    btn.title = kText("更多")
                }
            }
            viewModel.request(title: sender.title ?? "")
        }
    }
    
    func moreClick(period: String, popView: UIView) {
        dPrint("点击了"+period)
        for btn in self.selectBtnArr {
            if btn.buttonType != .normal {
                btn.title = period
                btn.isSelected = true
            }else {
                btn.isSelected = false
            }
        }
        viewModel.request(title: period)
        if let popView = PopView.popView(subView: popView) {
            popView.dismiss()
        }
    }
    
    @objc func buyBtnAction(sender:UIButton) {
        var isBuyBool:Bool = false
        if buyButton == sender {
            isBuyBool = true
        }else {
            isBuyBool = false
        }
        self.dataSource.openSelect(isBuyBool:isBuyBool)
    }
    
}



extension LeveragedTradeView : CHKLineChartDelegate {
    
    func numberOfPointsInKLineChart(chart: CHKLineChartView) -> Int {
        return viewModel.dataArray.count
    }
    
    func kLineChart(chart: CHKLineChartView, valueForPointAtIndex index: Int) -> CHChartItem {
        let data = viewModel.dataArray[index]
        let item = CHChartItem()
        item.openPrice = CGFloat(data[0])
        item.closePrice = CGFloat(data[1])
        item.highPrice = CGFloat(data[2])
        item.lowPrice = CGFloat(data[3])
        item.vol = CGFloat(data[4])
        item.time = Int(data[5])
        return item
    }
    
    func kLineChart(chart: CHKLineChartView, labelOnYAxisForValue value: CGFloat, atIndex index: Int, section: CHSection) -> String {
        var strValue = ""
        if section.key == "volume" {
            if value / 1000 > 1 {
                strValue = (value / 1000).ch_toString(maxF: section.decimal) + "K"
            } else {
                strValue = value.ch_toString(maxF: section.decimal)
            }
        } else {
            strValue = value.ch_toString(maxF: section.decimal)
        }
        
        return strValue
    }
    
    func kLineChart(chart: CHKLineChartView, labelOnXAxisForIndex index: Int) -> String {
        let data = viewModel.dataArray[index]
        let timestamp = Int(data[5])
        let dayText = Date.ch_getTimeByStamp(timestamp, format: "MM/dd HH:mm")
        return dayText
    }
    
    func kLineChart(chart: CHKLineChartView, decimalAt section: Int) -> Int {
        if section == 0 {
            return 8
        } else {
            return 2
        }
    }
    ///当前选中
    func kLineChart(chart: CHKLineChartView, didSelectAt index: Int, item: CHChartItem) {
        
    }
    
    ///切换分区的k线类型
    func kLineChart(chart: CHKLineChartView, didFlipPageSeries section: CHSection, series: CHSeries, seriesIndex: Int) {
    }
    
}


extension LeveragedTradeView: KlineViewModelDelegate {
    
    func socketTickDataChange() {
        
        
        
        let high = self.infoLabels[0]
        let low = self.infoLabels[1]
        let volume = self.infoLabels[2]
        
        if let last = viewModel.dataArray.last {
            high.text = "\(last[2])"
            low.text = "\(last[3])"
        }
        
        if self.chartView.rangeTo == viewModel.dataArray.count - 1{
            self.chartView.reloadData(toPosition: .end, resetData: true)
        }else {
            self.chartView.reloadData()
        }
        let vol = viewModel.coinModel.vol
        let price = viewModel.coinModel.price
        let open = viewModel.coinModel.open
        let money = viewModel.coinModel.money

        volume.text = "\(Int(vol))"

        self.numberLabel.text = "\(price)"
        
        var per: Double = 0
        if open != 0 {
            per = fabs((price - open) * 100 / open)
        }
        var pers = String(format: "%0.2f", per)
        if price >= open {
            pers = "+\(pers)%"
            self.numberLabel.textColor = kGreenColor
            self.flyLabel.textColor = kGreenColor
        }else {
            pers = "-\(pers)%"
            self.numberLabel.textColor = kGreenColor
            self.flyLabel.textColor = kGreenColor
        }
        self.flyLabel.text = pers

        let moneyStr = String(format: "%.2f", money)
        
        if AppCacheInfo.default.currency == "USD" {
            self.moneyLabel.text = "≈$ \(moneyStr)"
        }else {
            self.moneyLabel.text = "≈￥ \(moneyStr)"
        }
    }
    func socketChartDataChange(isTimeLine: Bool) {
        self.socketTickDataChange()
        if isTimeLine {
            self.chartView.setSerie(hidden: true, inSection: 0)
            self.chartView.setSerie(hidden: true, inSection: 1)
            self.chartView.setSerie(hidden: false, by: CHSeriesKey.timeline, inSection: 0)
            self.chartView.setSerie(hidden: false, by: "timelineMA", inSection: 0)
            self.chartView.setSerie(hidden: false, inSection: 1)
        }else {
            self.chartView.setSerie(hidden: true, inSection: 0)
            self.chartView.setSerie(hidden: true, inSection: 1)
            self.chartView.setSerie(hidden: false, by: CHSeriesKey.candle, inSection: 0)
            self.chartView.setSerie(hidden: false, by: "priceMA", inSection: 0)
            self.chartView.setSerie(hidden: false, inSection: 1)
        }
        self.chartView.reloadData(toPosition: .end, resetData: true)
    }
    
    func socketDepthDataChange(askPrice: Double, bidPrice: Double) {
        self.buyButton?.setTitle("\(kText("买入")) \(askPrice)", for: .normal)
        self.sellButton?.setTitle("\(kText("卖出")) \(bidPrice)", for: .normal)
    }
    
    func socketDataError() {

    }
    
}

extension LeveragedTradeView: PopViewDelegate {
    func willDismiss() {
        for btn in self.selectBtnArr {
            btn.backgroundColor = UIColor.clear
        }
    }
}
